//简单的服务器中间件

'use strict';
var connect = require('connect')
    , http = require('http')
    , https = require('https');

//customMiddlewars
function logger(req, res, next) {
    console.log('%s %s', req.method, req.url);
    next();//前往下个中间件
}
//默认是text/plain，如果设置了不当的，get请求是会返回不识别
function httpheader(req,res,next) {
    res.setHeader('content-type', 'text/plain; charset=utf-8');
    //res.json(data);
    next();
}

function restrict(req,res,next) {
    var authorization =req.headers.authorization;
    //authorization没有
    if(!authorization) return next (new Error('Unauthorzied'));

    var parts =authorization.split('');//分割成字符串数组
    var scheme =parts[0]
    var auth =new Buffer(part[1],'base64').toString().split(':');//过滤掉：并且拆分成字符串返回字符串数组
    var user =auth[0];
    var pass =auth[1];

    authenticateWithDatabase(user,pass,function (err) {
        if (err) return next(err); //告诉分派器出错了
        next();
    })
}
//app.use(bodyParser.urlencoded({extended: false})); post 设置extended:true
function end(req,res) {
    res.end('set httpheader');
}
var app = connect();

//服务器开启Gzip
// var compression = require('compression');
// app.use(compression());
//var headers = request.headers
//然后服务端判断是否支持gzip if(headers['accept-encoding'] || '').indexOf('gzip') != -1)

//压栈
app.use(logger);
app.use(httpheader);
app.use(restrict);
app.use(end);
app.listen(3000);  //可以访问127.0.0.1:3000/